package com.example.test015;

import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//      1. 获取一个线程池对象
        ExecutorService es = Executors.newCachedThreadPool();

//      2. 创建Callable类型的任务对象
        Future<Integer> submit = es.submit(new MyCall(2, 5));

//      3.  判断任务是否已经完成
        boolean done = submit.isDone();
        System.out.println("第一次判断任务是否完成："+done);

//      4.判断任务是否已经被取消
        boolean cancelled = submit.isCancelled();
        System.out.println("第一次判断任务是否取消："+cancelled);

//      5.无限期等待结果，  直到完成为止
        Integer integer = submit.get();
        System.out.println("任务执行的结果是："+integer);

         done = submit.isDone();
        System.out.println("第二次判断任务是否完成："+done);

        cancelled = submit.isCancelled();
        System.out.println("第二次判断任务是否取消："+cancelled);

//        *************************************
    }
}

class MyCall implements Callable<Integer> {

    private  int a;
    private  int b;


    @Override
    public Integer call() throws Exception {
        String name = Thread.currentThread().getName();
        System.out.println(name+"准备开始....");
        Thread.sleep(2000);
        System.out.println(name+"计算完成....");
        return a+b;
    }

    public MyCall(int a, int b) {
        this.a = a;
        this.b = b;
    }
}
